package com.test.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

public class UserRealm extends AuthorizingRealm{

    /**
     * 授权逻辑
     */
    /**
     * 执行授权逻辑
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        System.out.println("执行授权逻辑");

        //给资源进行授权
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //获取当前用户
        Subject subject= SecurityUtils.getSubject();
        System.out.println("当前登录用户：" + subject.getPrincipal());
        //添加资源的授权字符串
        info.addStringPermission("user:add");

        return info;
    }
    /**
     * 认证逻辑
     */
    /**
     * 认证逻辑
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");

        //先写模拟数据进行验证，下一步再连接数据库，假设数据库的用户名和密码如下
        String dbusername = "admin";
        String dbpassword = "admin";

        //编写shiro判断逻辑，判断用户名和密码
        //1. 判断用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        if (!token.getUsername().equals(dbusername)) {
            //用户名不存在shiro底层会抛出UnknownAccountException
            return null;
        }
        User user = new User();
        user.setPassword(dbpassword);
        user.setUsername(dbusername);
        //2. 判断密码,参数1：需要返回给login方法的数据；参数2：数据库密码，shiro会自动判断
        return new SimpleAuthenticationInfo(user, dbpassword, "");
    }

}